package Scuttlebutt;

import java.awt.datatransfer.*;
import java.awt.dnd.*;
import java.lang.*;
import java.io.*;
import javax.swing.*;
import java.net.URL;
import java.util.*;

import javax.swing.tree.TreePath;

public class TreeDropTargetListener implements DropTargetListener 
{
	Scuttlebutt parent = null;
	

	public TreeDropTargetListener(Scuttlebutt parent)
	{
		this.parent = parent;
	}

	public void dragEnter(DropTargetDragEvent d0)
	{
	}

	public void dragExit(DropTargetEvent d0)
	{
	}

	public void dragOver(DropTargetDragEvent d0)
	{
		TreePath loc = parent.getProject().getTree().getPathForLocation(d0.getLocation().x, d0.getLocation().y);
		if(loc != null){
			Object o = loc.getLastPathComponent();
	        if (o instanceof FolderNode ) {
				parent.getProject().getTree().setSelectionPath(loc);
	        }else{
		        parent.getProject().getTree().setSelectionPath(null);
	        }
		}
	}

	public void drop(DropTargetDropEvent d0)
	{
		d0.acceptDrop(d0.getDropAction());
		Transferable t = d0.getTransferable();
		DataFlavor [] f = t.getTransferDataFlavors();
		DataFlavor dfurl = null;
		DataFlavor df_node = null;
		DataFlavor dffl = null;
		try{
			dfurl = new DataFlavor("application/x-java-url; class=java.net.URL");
			df_node = new DataFlavor("application/node");
			dffl = new DataFlavor("application/x-java-file-list; class=java.util.List");
			
		}catch(java.lang.ClassNotFoundException cnf){
		}
		
		for(DataFlavor d : f){
			try{
				if(d.isFlavorRemoteObjectType()){
					System.out.println("DataFlavor remote object type");
				}
//				System.out.println("MimeType:" + d.getMimeType());
				if(dfurl.isMimeTypeEqual(d)){
					String link = t.getTransferData(d).toString();
					
//					TreePath loc = parent.getProject().getTree().getPathForLocation(d0.getLocation().x, d0.getLocation().y);
					FolderNode o = (FolderNode)parent.getProject().getTree().getSelectionPath().getLastPathComponent();
					
					for (Enumeration e = o.children() ; e.hasMoreElements() ;) {
						Object child = (Object)e.nextElement();
			        	if (child instanceof URLNode ) {
				        	if(((URLNode)child).getURL().compareToIgnoreCase(link) == 0){
					        	return;
				        	}
			        	}
					}
			        StringInputDialog dlg = new StringInputDialog(type.link, parent, "Web Link", "Link:", link);
	    			dlg.setVisible(true);
			        String str = null;
			        if(dlg.bState){
				        str = dlg.getValue();
			        }else{
				        return;
			        }
					/*URLNode node = new URLNode(str, t.getTransferData(d).toString());
					node.setURL(true);
					o.addSortable(node);*/
					o.addURLNode(str, t.getTransferData(d).toString());
					parent.saveProject();
					parent.updateTree();
				}else if(d.isMimeTypeEqual(df_node)){
					Object o = t.getTransferData(d);
					
			        if (o instanceof FolderNode ) {
				        FolderNode folder = (FolderNode)o;
					    if(parent.isConnected()){
					        Object p = parent.getProject().getTree().getSelectionPath().getLastPathComponent();
					  		if (p instanceof FolderNode ){
							  	FolderNode dest = (FolderNode)p;
				        		folder.move(parent,dest);
					        }
					    }
			        } else if (o instanceof URLNode ){
				        URLNode node = (URLNode)o;
				        Object p = parent.getProject().getTree().getSelectionPath().getLastPathComponent();
				        
				        if (p instanceof FolderNode ){
				     	   node.removeFromParent();
				     	   ((FolderNode)p).addSortable(node);
				     	   parent.updateTree();
				     	   parent.saveProject();
				        }
						
			        }else if (o instanceof SortableNode ){
				        System.out.println("dropped node");
				        if((!((SortableNode)o).getUploadingState()) && (((SortableNode)o).isUploaded())){
					        SortableNode node = (SortableNode)o;
					        Object p = parent.getProject().getTree().getSelectionPath().getLastPathComponent();
					        if (p instanceof FolderNode ){
						        node.move(parent, ((FolderNode)p));
						        return;
					        }
				        }else{
					        if(((SortableNode)o).getUploadingState()){
	        		        	JOptionPane.showMessageDialog(null, "You cannot move files while uploading.", "Upload error", JOptionPane.ERROR_MESSAGE);
				        	}else if(!((SortableNode)o).isUploaded()){
					        	JOptionPane.showMessageDialog(null, "You must upload files before moving them.", "Upload error", JOptionPane.ERROR_MESSAGE);
				        	}else{
	        		        	JOptionPane.showMessageDialog(null, "You cannot move files.", "Not Connected Error", JOptionPane.ERROR_MESSAGE);
					        }
				        }
			        }
		        }else if(d.isFlavorJavaFileListType()){
			        System.out.println("dropped file");
				  	Object p = parent.getProject().getTree().getSelectionPath().getLastPathComponent();
				  	System.out.println("dropped into " + p.toString());
				  	
				    if (p instanceof FolderNode ){
					    FolderNode folder = (FolderNode)p;
					    System.out.println("is folder");
						List fileList = (List)t.getTransferData(d);
						int copy_count = 0;
						String msg = new String();
						for (int i = 0; i < fileList.size(); i++) {
							File data = (File)fileList.get(i);
							if(data.isDirectory()){
							}else{
								System.out.println("folder path:" + folder.getNodePath());
								File nFile = null;
								String path = new String(folder.getNodePath() + File.separatorChar + data.getName());
								System.out.println("new path:" + path); 
								nFile = new File(path);
								
								if(nFile.exists()){
									System.out.println(nFile.getPath() + " already exists");
//									JOptionPane.showMessageDialog(parent, new String("File " + nFile.getPath() + " already exists"), "Error", JOptionPane.ERROR_MESSAGE);
								//	return;
								}else{
								//copy file
									copy_count++;
									copy(data, nFile);
									
								/*	try{
										if(data.renameTo(nFile)){
							//				System.out.println("renaming succeeded");
										}else{
							//				System.out.println("renaming failed");
										}
									}catch(java.lang.Exception e){
										System.err.println("Exception:" + e);
									}*/
								
								
									msg += data.getName();
									msg += "\n";
								//move file
								/*if(data.renameTo(nFile)){
									System.out.println("renaming succeeded");
								}else{
									System.out.println("renaming failed");
								}*/
								
						
						       	 	System.out.println("file dropped:" + nFile.getPath());
						       	 	SortableNode node = new SortableNode(data.getName(), nFile.getPath());
						       	 	node.setUploaded(false);
									String remote_dir = null;
									if(folder.getRemoteDirectory().length() == 0){
										remote_dir = new String(folder.toString());
									}else{
										remote_dir = new String(folder.getRemoteDirectory() + File.separatorChar + folder.toString());
									}
									node.setRemoteDirectory(remote_dir);
						 		   	folder.addSortable(node);
					 		   		parent.updateTree();
								}
							}
						}
						if(copy_count > 0){
							JOptionPane.showMessageDialog(null, "Copy:\n" + msg + "complete.", "OK", JOptionPane.PLAIN_MESSAGE);
						}
					}
				}else{
//					System.out.println("none of the above:" + t.getTransferData(d).toString());
				}
			}catch(UnsupportedFlavorException e){
				System.err.println(e.getMessage());
			}catch(IOException e){
				System.err.println(e.getMessage());
//			}catch(BadLocationException ble){
//				System.err.println(ble.getMessage());
			}
		}
	}

	public void dropActionChanged(DropTargetDragEvent d0)
	{
	}
	


/*class CopyThread extends Thread{	
	File source = null;
	File dest = null;
	JOptionPane pane = null;
	public CopyThread(File source, File dest){
		this.source = source;
		this.dest = dest;
		pane = new JOptionPane();
	}
	
	public void run(){
		pane.showMessageDialog(null, "Message", "Copying file", JOptionPane.ERROR_MESSAGE);
	}
	
	public void kill(){
		pane.hide();
	}
}
*/
	
	protected void copy(File source, File dest) {
//		CopyThread t = new CopyThread(source, dest);
//		t.start();
		try{
			FileWriter b = new FileWriter(dest);
			BufferedWriter w = new BufferedWriter(b);
	//		w.write(getText(), 0, getText().length());
			BufferedReader r = new BufferedReader(new FileReader(source));
			
	 		int val = 0;
			while( (val = r.read()) != -1){
	//	 		buffer.append((char)val);
				w.write(val);
	 		}
	 		r.close();
			w.close();
			b.close();
			
			r = null;
			w = null;
			b = null;
		}catch(IOException e){
		}
//		t.kill();
	}
}

